﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Dependency_Injection
{
  public  class UsersService
    {
        private readonly UserContxt _usersContext;
        //数据上下文，通过构造函数注入 到私有变量_booksContext中
        public UsersService(UserContxt context) => _usersContext = context;
        //下列所有关于数据库上下文的操作，都是使用私有变量booksContext

        public async Task CreateTheDatabaseAsync()
        {
            //实例化上下文对象
            //context.Database可用于创建和删除数据库，并直接发送SQL语句
            //EnsureCreatedAsync方法确保创建了数据库。如果数据库已经存在，此方法返回false .
            //若数据库不存在，择根据上下文合模型定义创建数据库
            bool created = await _usersContext.Database.EnsureCreatedAsync();
            //根据created显示数据库是否存在
            string creationInfo = created ? "created" : "exists";
            System.Console.WriteLine($"database {creationInfo}");
        }
        public async Task AddBooksAsync()
        {
            var b1 = new User
            {
                Name = "用户一号",
                Sex = "男",
                Age =20
            };
            var b2 = new User
            {
                Name = "用户二号",
                Sex = "男",
                Age = 22
            };
            var b3 = new User
            {
                Name = "用户一三号",
                Sex = "女",
                Age = 18
            };

            _usersContext.AddRange(b1, b2, b3);
            int records = await _usersContext.SaveChangesAsync();
            Console.WriteLine($"{records} records added");
        }

        public async Task ReadBooksAsync()
        {
            List<User> books = await _usersContext.Users.ToListAsync();
            foreach (var b in books)
            {
                Console.WriteLine($"{b.Name} {b.Sex}{b.Age}");
            }
            Console.WriteLine();
        }
    }
}
